package com.problem.leetcode;

import com.google.common.base.Stopwatch;

/**
 * 解法:双指针，一个指向非0，一个指向0，
 * 头指针判断是否为0，不为0则调换，尾指针判断是否是非0，如果是则调换
 *
 * @author didi
 * @DESCRIPTION
 * @create 2019-04-26 15:18
 **/

public class Problem283 {
    public void moveZeroes(int[] nums) {

        int zeroIndex = 0, numIndex = 0;

        while (zeroIndex < nums.length && numIndex < nums.length && numIndex >= zeroIndex) {
            for (; zeroIndex < nums.length; zeroIndex++) {
                if (nums[zeroIndex] == 0) {
                    break;
                }
            }

            for (; numIndex < nums.length; numIndex++) {
                if (nums[numIndex] != 0) {
                    break;
                }
            }

            if (numIndex < nums.length && zeroIndex < nums.length && numIndex > zeroIndex && nums[zeroIndex] == 0 &&
                nums[numIndex] != 0) {
                swap(nums, zeroIndex, numIndex);
                ++numIndex;
            }

        }

    }

    private void swap(int[] nums, int beginIndex, int endIndex) {
        int tmp = nums[beginIndex];
        nums[beginIndex] = nums[endIndex];
        nums[endIndex] = tmp;
    }

    public static void main(String[] args) {
        Stopwatch  stopwatch  = Stopwatch.createStarted();
        Problem283 problem283 = new Problem283();
        for (int index = 0; index < 10000000; index++) {
            problem283.moveZeroes(new int[]{0, 1, 0, 3, 12});
        }
        stopwatch.stop();
        System.out.println(stopwatch.toString());
    }

}
